module.exports = class extends think.Model {
  /**
   *
   * @param type
   * @param fid
   * @param field
   * @returns {Promise<[]>}
   */
  async list({ type = "list", fid = 0, field = "*" }) {
    const list = await this.field(field)
      .order("sort")
      .select();
    let result = [];
    // 是否有子菜单
    const hasChildren = id => list.filter(r => r.fid === id);
    // 递归获取list结构
    const getList = fid => {
      const res = list.filter(r => r.fid === fid);
      res.forEach(r => {
        result.push(r);
        if (hasChildren(r.id)) {
          getList(r.id);
        }
      });
    };

    const getTree = fid => {
      const res = list.filter(r => r.fid === fid);
      res.forEach(r => {
        if (hasChildren(r.id)) {
          r.children = getTree(r.id);
        }
      });
      return res;
    };

    if (type === "list") {
      getList(fid);
    } else if (type === "tree") {
      result = getTree(fid);
    }

    return result;
  }
};
